package com.atguigu.interceptor;

import com.alibaba.druid.support.json.JSONUtils;
import com.atguigu.utils.JWTUtils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        //从请求头中获取token
        String token = request.getHeader("token");

        try {
            JWTUtils.verifyToken(token);//验证令牌
//            map.put("msg","验证通过!");
//            map.put("status",true);
            return true;//放行请求
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token以过期!");
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg","签名错误!");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","加密算法不匹配!");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","无效token!");
        }
        map.put("status",false);
        //将map转为json，响应出去
        String jsonString = JSONUtils.toJSONString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(jsonString);
        return false;
    }
}
